package com.example.tys.baseapplication.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;

import java.util.List;

/**
 * @author tys
 * @date 2019/4/12
 */

public class NetworkUtils {

    /**
     * 当前是否连接网络(wifi或4G)
     *
     * @param context
     * @return true 已经连接网络
     */
    public static boolean isActiveNetwork(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 当前网络类型(只判断了wifi和4g)
     *
     * @param context
     * @return {@link ConnectivityManager#TYPE_WIFI} {@link ConnectivityManager#TYPE_MOBILE}
     */
    public static int getCurrentNetType(Context context) {
        final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (wifiNetworkInfo != null && wifiNetworkInfo.isAvailable() && wifiNetworkInfo.isConnected()) {
            return ConnectivityManager.TYPE_WIFI;
        } else if (mobileNetworkInfo != null && mobileNetworkInfo.isAvailable() && mobileNetworkInfo.isConnected()) {
            return ConnectivityManager.TYPE_MOBILE;
        } else {
            return -1;
        }
    }

    /**
     * 需要开通定位权限
     *
     * @param context
     * @return
     */
    public @Nullable
    static List<ScanResult> getWifiList(Context context) {
        List<ScanResult> scanResults = null;
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            scanResults = wifiManager.getScanResults();
        }
        return scanResults;
    }

    public @Nullable
    static WifiInfo getCurrentWifiInfo(Context context) {
        WifiInfo connectionInfo = null;
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            connectionInfo = wifiManager.getConnectionInfo();
        }
        return connectionInfo;
    }


}
